package com.trusfort.redis;



import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.params.ScanParams;
import redis.clients.jedis.resps.ScanResult;

/**
 * Redis服务工具类
 *
 * @author DangT
 * @date 2017年5月11日 下午4:30:37
 * @version V1.0
 */
public class RedisServiceUtil {
	private RedisServiceUtil() {
		throw new IllegalStateException("Utility class");
	}


	private static final String USAGE_MODE_SENTINEL = "sentinel";
	private static final String USAGE_MODE_CLUSTER = "cluster";
	private static final String USAGE_MODE_SINGLE = "single";
	private static final String USAGE_MODE = "single"; //single
	public static final String KEY_PREFIX = "XDID";
	public static final String KEY_SEPARATOR = ":";

	private static RedisService service;

//	static {
//		try {
//			init();
//		} catch (Exception e) {
//			//logger.warn("", e);
//		}
//	}

	/**
	 * 初始化Redis
	 *
	 */
	public static void init(String usageMode,String hostAndPort,String passwd) throws RedisException {

		try {
//			if (service == null) {
				if (USAGE_MODE_CLUSTER.equals(usageMode)) { // Cluster模式
//					service = RedisClusterService.init(hostAndPort,passwd);
					service = RedisClusterService.getInstance(hostAndPort, passwd);
				} else if (USAGE_MODE_SINGLE.equals(usageMode)) { // Cluster模式
					service = RedisDirectService.init(hostAndPort,passwd);
				}
//			}
		} catch (Exception e) {
//			logger.error("Initialize redis service error!", e);
			throw new RedisException(e);
		}

	}
	
	
	public static void set(String key, String value) throws Exception {

		service.set(key, value);

	}

	public static void set(Integer dbIndex, String key, String value) throws Exception {

		set(key, value);
		
	}

	public static void set(String key, String value, int seconds) throws Exception {

		service.set(key, value,seconds);

	}

	public static void set(Integer dbIndex, String key, String value, int seconds) throws Exception {

		set(key, value, seconds);
		
	}
	
	
	public static void set(List<String> list, int seconds) throws Exception{
	
		service.set(list, seconds);
	}
	
	
	public static void del(Integer dbIndex,List<String> list) throws Exception {
		
//		init("cluster","172.10.3.110:6379,172.10.3.110:6479,172.10.3.110:6579,172.10.3.110:6679,172.10.3.110:6779,172.10.3.110:6879","123456");
		service.del(dbIndex, list);
	}
	
	public static ScanResult<String> scan(Integer dbIndex, final String key,String cursor,Integer count) throws Exception{
		 
		return service.scan(dbIndex, key, cursor, count);
	}
   

	public static void close() {

		if (service != null) {
			service.close();
		}

	}
	  

	public static Long ttl(final String key){

		try {
			return service.ttl(key);
		} catch (Exception e) {
			return 0L;
		}
	}
}
